<?php

error_reporting(E_ALL);
set_time_limit(0);

$address = '127.0.0.1';
$port    = 10013;

/**
 * 创建socket句柄
 * 协议 AF_INET
 * socket类型 SOCK_STREAM
 * 公共协议类型 SOL_TCP
 */
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or returnError('socket_create');


/**
 * 绑定ip与端口
 */
socket_bind($sock, $address, $port);

/**
 * 监听
 */
socket_listen($sock);

p('Server is start work and listen ' . $port . '!');


//socket_set_nonblock($sock);

do {
	echo 'doing.........'.PHP_EOL;
	$connection = socket_accept($sock);

	if ($connection) {
		p('have a new client connecting');
		$welcome = 'Welcome My chat' . PHP_EOL;
		socket_send($connection, $welcome, strlen($welcome), MSG_EOF);
		$buf = socket_read($connection, 8000);
		if ($buf) {
			$res = '已经收到消息: '.$buf.PHP_EOL;
			p('received new message:' . $buf);
			socket_write($connection, $res,0);
		}
		socket_close($connection);
	}

	sleep(1);
} while (true);


/**
 * 关闭连接
 */
socket_close($sock);

function returnError($action) {
	die($action . ' failed :reason:' . socket_strerror(socket_last_error()) . "\n");
}

function p($str) {
	echo $str . PHP_EOL;
}